/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.bluetooth.le;

import android.app.Activity;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

public class MeasumentActivity extends Activity {
    private final static String TAG = MeasumentActivity.class.getSimpleName();

    public static final String EXTRAS_DEVICE_NAME = "DEVICE_NAME";
    public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS";

    private boolean mStateMeasument = false;
    private String mDeviceName;
    private String mDeviceAddress;
    private TextView mMeasumentField;
    private Button mMeasumentStart;
    private Button mMeasumentStop;
    private BluetoothLeService mBluetoothLeService;
    private ArrayList<ArrayList<BluetoothGattCharacteristic>> mGattCharacteristics =
            new ArrayList<ArrayList<BluetoothGattCharacteristic>>();
    private boolean mConnected = false;
    private BluetoothGattCharacteristic mNotifyCharacteristic = null;

    private final ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected( ComponentName componentName, IBinder service ) {
            mBluetoothLeService = ( (BluetoothLeService.LocalBinder) service ).getService();
            if ( !mBluetoothLeService.initialize() ) {
                Log.e( TAG, "Unable to initialize Bluetooth" );
                finish();
            }
            // Automatically connects to the device upon successful start-up initialization.
            mBluetoothLeService.connect( mDeviceAddress );
        }

        @Override
        public void onServiceDisconnected( ComponentName componentName ) {
            mBluetoothLeService = null;
        }
    };

    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive( Context context, Intent intent ) {
            final String action = intent.getAction();
            if ( BluetoothLeService.ACTION_GATT_CONNECTED.equals( action ) ) {
                mConnected = true;
                updateConnectionState( R.string.connected );
                invalidateOptionsMenu();
            } else if ( BluetoothLeService.ACTION_GATT_DISCONNECTED.equals( action ) ) {
                mConnected = false;
                updateConnectionState( R.string.disconnected );
                invalidateOptionsMenu();
                clearUI();
            } else if ( BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals( action ) ) {
                // Show all the supported services and characteristics on the user interface.
//                displayGattServices( mBluetoothLeService.getSupportedGattServices() );
                Toast.makeText( getApplicationContext(), "ACTION DISCOVERED", 0 ).show();
            } else if ( BluetoothLeService.ACTION_DATA_AVAILABLE.equals( action ) ) {
                displayData( intent.getStringExtra( BluetoothLeService.EXTRA_DATA ) );
            }
        }
    };

    private final OnClickListener mOnClickListener = new OnClickListener() {

        @Override
        public void onClick( View v ) {
            if ( v == mMeasumentStart ) {
                mStateMeasument = true;
                mMeasumentStart.setEnabled( false );
                mMeasumentStop.setEnabled( true );

            } else if ( v == mMeasumentStop ) {
                mStateMeasument = false;
                mMeasumentStart.setEnabled( true );
                mMeasumentStop.setEnabled( false );


            }
        }
    };


    private void clearUI() {
        mMeasumentField.setText( R.string.no_data );
    }

    @Override
    public void onCreate( Bundle savedInstanceState ) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_heartrate_measurment );

        final Intent intent = getIntent();
        mDeviceName = intent.getStringExtra( EXTRAS_DEVICE_NAME );
        mDeviceAddress = intent.getStringExtra( EXTRAS_DEVICE_ADDRESS );

        // Sets up UI references.
        ( (TextView) findViewById( R.id.device_address ) ).setText( mDeviceAddress );
        mMeasumentField = (TextView) findViewById( R.id.heart_rate_text );
        mMeasumentStart = (Button) findViewById( R.id.button_start_measument );
        mMeasumentStop = (Button) findViewById( R.id.button_stop_measument );

        getActionBar().setTitle( mDeviceName );
        getActionBar().setDisplayHomeAsUpEnabled( true );
        Intent gattServiceIntent = new Intent( this, BluetoothLeService.class );
        bindService( gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE );

        mBluetoothLeService.setCharacteristicNotification( mNotifyCharacteristic
                , true );
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver( mGattUpdateReceiver, makeGattUpdateIntentFilter() );
        if ( mBluetoothLeService != null ) {
            final boolean result = mBluetoothLeService.connect( mDeviceAddress );
            Log.d( TAG, "Connect request result=" + result );
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver( mGattUpdateReceiver );
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService( mServiceConnection );
        mBluetoothLeService = null;
    }

    @Override
    public boolean onCreateOptionsMenu( Menu menu ) {
        getMenuInflater().inflate( R.menu.gatt_services, menu );
        if ( mConnected ) {
            menu.findItem( R.id.menu_connect ).setVisible( false );
            menu.findItem( R.id.menu_disconnect ).setVisible( true );
        } else {
            menu.findItem( R.id.menu_connect ).setVisible( true );
            menu.findItem( R.id.menu_disconnect ).setVisible( false );
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected( MenuItem item ) {
        switch ( item.getItemId() ) {
            case R.id.menu_connect:
                mBluetoothLeService.connect( mDeviceAddress );
                return true;
            case R.id.menu_disconnect:
                mBluetoothLeService.disconnect();
                return true;
            case android.R.id.home:
                onBackPressed();
                return true;
        }
        return super.onOptionsItemSelected( item );
    }

    private void updateConnectionState( final int resourceId ) {
//        runOnUiThread( new Runnable() {
//            @Override
//            public void run() {
//                mConnectionState.setText( resourceId );
//            }
//        } );
    }

    private void displayData( String data ) {
        if ( data != null ) {
            mMeasumentField.setText( data );
        }
    }

    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction( BluetoothLeService.ACTION_GATT_CONNECTED );
        intentFilter.addAction( BluetoothLeService.ACTION_GATT_DISCONNECTED );
        intentFilter.addAction( BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED );
        intentFilter.addAction( BluetoothLeService.ACTION_DATA_AVAILABLE );
        return intentFilter;
    }
}
